import React, { useState, useEffect } from 'react'
import { getNewsList } from './api'
import style from './News.module.css'
import timestampToTime from '../../utils/formatDate'
import { useNavigate } from 'react-router-dom'
const { newBox } = style
const News = () => {
  const navigate = useNavigate()
  //储存新闻
  const [newsList, setnewsList] = useState([])
  const getNew = async () => {
    await getNewsList().then(res => {
      setnewsList(res.data)
    })
  }
  //获取新闻
  useEffect(() => {
    getNew()
  }, [])
  return (
    <div>
      {newsList.map(item => (
        <div
          key={item.id}
          className={newBox}
          onClick={() => {
            navigate(`/detail/${item.id}`, {
              state: {
                title: item.title,
                contents: item.content,
                imgUrl: item.imgUrl,
                date: timestampToTime(item.create_time * 1),
              },
            })
          }}
        >
          <img src={item.imgUrl} alt="" />
          <div>
            <h2>{item.title}</h2>
            <p>{item.content}</p>
            <span>{timestampToTime(item.create_time * 1)}</span>
          </div>
        </div>
      ))}
    </div>
  )
}

export default News
